<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <form action="/" class="formSearch">
      <van-search
        v-model="searchText"
        show-action
        shape="round"
        background="#40a1ff"
        placeholder="请输入搜索关键词"
        @focus="isResultShow = false"
        @search="onSearch(searchText)"
        @cancel="$router.back()"
      />
    </form>
    <!-- /搜索栏 -->

    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :search-text="searchText" />
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <search-suggestion v-else-if="searchText" :search-text="searchText" @search="onSearch" />
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <search-history
      v-else
      :search-history="searchHistory"
      @search="onSearch"
      @update-history="searchHistory = $event"
    />
    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import SearchResult from './components/search-result'
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import { setItem, getItem } from '@/utils/storeage'
// import { getSearchHistories } from '@/api/search'
// import { mapState } from 'vuex'

export default {
  name: 'SearchIndex',
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  props: {},
  data() {
    return {
      // 搜索输入框的内容
      searchText: '',
      // 控制搜索结果的显示状态
      isResultShow: false, // 控制加载
      // 搜索历史数据
      searchHistory: []
    }
  },
  computed: {
    // ...mapState(['user'])
  },
  watch: {
    searchHistory() {
      // 监视搜索历史记录的变化，存储到本地存储
      setItem('search-history', this.searchHistory)
    }
  },
  created() {
    this.loadSearchHistory()
  },
  mounted() {},
  // 方法集合
  methods: {
    onSearch(searchText) {
      this.searchText = searchText

      const index = this.searchHistory.indexOf(searchText)
      if (index !== -1) {
        // 把重复项删除
        this.searchHistory.splice(index, 1)
      }
      // 记录搜索历史记录
      this.searchHistory.unshift(searchText)

      // 如果用户已登录，则把搜索历史记录存储到线上

      // 如果没有登录页，则把搜索页面存储到本地
      // setItem('search-history', this.searchHistory)

      // 展示搜索结果
      this.isResultShow = true
    },
    async loadSearchHistory() {
      // 如果用户已登录
      const searchHistories = getItem('search-history') || []
      //   if (this.user) {
      //     const { data } = await getSearchHistories()

      //     // 合并数组:
      //     // [...数组，...数组]
      //     // 把Set转为数组: [...Set对象]
      //     // 数组去重: [...new Set([...数组，...数组])
      //     searchHistories = [...new Set([...searchHistories, ...data.data.keywords])]
      //   }
      this.searchHistory = searchHistories
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
  .van-search__action {
    color: #fff;
  }
}
</style>
